package com.cmpe.group6.storyroad;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import android.app.Fragment;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.Toast;

import com.cmpe.group6.storyroad.ListAdapters.NotificationsAdapter;
import com.cmpe.group6.storyroad.jsonClasses.NotificationHolder;
import com.cmpe.group6.storyroad.jsonClasses.NotificationObject;
import com.google.gson.Gson;

/**
 * A simple {@link android.support.v4.app.Fragment} subclass. Activities that
 * contain this fragment must implement the
 * {@link NotificationsFragment.OnFragmentInteractionListener} interface to
 * handle interaction events. Use the {@link NotificationsFragment#newInstance}
 * factory method to create an instance of this fragment.
 * 
 */
public class NotificationsFragment extends Fragment {

	private List<NotificationObject> notifications;
	private ListView notificationList;
	private static NotificationsAdapter adapter;
	private NotificationTask nTask;
	private ProgressBar bar;

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		// Inflate the layout for this fragment

		View holder = inflater.inflate(R.layout.tab3, container, false);
		bar = (ProgressBar) holder.findViewById(R.id.progressBar1);
		notificationList = (ListView) holder.findViewById(R.id.listView1);
		notifications = new ArrayList<NotificationObject>();

		nTask = new NotificationTask();
		nTask.execute((Void) null);

		return holder;
	}

	@Override
	public void onViewCreated(View view, Bundle savedInstanceState) {
		super.onViewCreated(view, savedInstanceState);

		// Clicking an item on this list will direct the user to either profile
		// or story page.
		notificationList
				.setOnItemClickListener(new AdapterView.OnItemClickListener() {

					@Override
					public void onItemClick(AdapterView<?> arg0, View arg1,
							int position, long arg3) {

						Object temp = notificationList
								.getItemAtPosition(position);
						if (temp instanceof String) {
							Intent profileIntent = new Intent(getActivity(),
									ProfileActivity.class);
							profileIntent.putExtra("targetname", (String) temp);
							startActivity(profileIntent);

						} else {
							Intent readStoryIntent = new Intent(getActivity(),
									ReadStoryActivity.class);
							readStoryIntent.putExtra("story_id",
									String.valueOf(temp));
							startActivity(readStoryIntent);
						}
					}
				});

	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
	}

	/**
	 * Represents an asynchronous Notification task for getting user's
	 * notifications from the server.
	 * 
	 */
	public class NotificationTask extends AsyncTask<Void, Void, Boolean> {

		@Override
		protected void onPreExecute() {
			bar.setVisibility(View.VISIBLE);
		}

		@Override
		protected Boolean doInBackground(Void... params) {
			DefaultHttpClient httpclient = new DefaultHttpClient();
			HttpPost httppost = new HttpPost(Utils.SERVER_NAME
					+ "Notifications");

			try {
				// Add your data
				List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(
						3);
				nameValuePairs.add(new BasicNameValuePair("request_type",
						"Android"));
				nameValuePairs.add(new BasicNameValuePair("username",
						Utils.username));
				httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

				// Execute HTTP Post Request
				HttpResponse response = httpclient.execute(httppost);

				String jsonResponse = EntityUtils
						.toString(response.getEntity());
				Gson gson = new Gson();
				NotificationObject[] result = gson.fromJson(jsonResponse,
						NotificationHolder.class).notifications;

				notifications = Arrays.asList(result);
				adapter = new NotificationsAdapter(getActivity(), notifications);

			} catch (ClientProtocolException e) {
				// TODO Auto-generated catch block
			} catch (IOException e) {
				// TODO Auto-generated catch block
			}

			return true;
		}

		@Override
		protected void onPostExecute(final Boolean success) {

			if (!success) {
				Toast.makeText(getActivity(), "Connection Error",
						Toast.LENGTH_SHORT).show();
			} else {
				notificationList.setAdapter(adapter);
				bar.setVisibility(View.GONE);
			}
		}

		@Override
		protected void onCancelled() {

		}
	}

}
